// pages/bargainDetails/bargainDetails.js

//获取app实例
const app = getApp();
var utils = require("../../utils/util.js");
var WxParse = require('../../wxParse/wxParse.js');
var noLogin = require("../template/noLogin.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    itemInfo: null, //页面信息
    isindicator: 0, //轮播图当前下标值
    isLay: false,  //弹层
    isShareLay: false,  //分享弹层
    isStep: 0,   //帮砍状态
    hasUserInfo: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!wx.getStorageSync('userInfo')) {
      noLogin.showNoLogin(this).then(() => {
        this.getBargainInfo(); //用户授权后更新用户数据
      }).catch(() => {
        this.setData({ hasUserInfo: false })
      });  //判断用户未登录，弹出授权窗口
    } else {
      this.setData({ hasUserInfo: true }); //判断用户已登录，关闭授权窗口
      if (app.globalData.userId && wx.getStorageSync('userId')){
        this.getBargainInfo();
      }else{
        app.userLogin(() => {
          this.getBargainInfo();  //用户信息存在本地  ----> 直接登录
        }); 
      }
    }
  },

  //用户确认授权
  WeChatUserInfo: function (e) {
    if (e.detail.userInfo) {
      this.setData({hasUserInfo: true});
      //发起登录
      //用户授权后更新用户数据
      noLogin.getUserInfo(this).then(() => {
        this.getBargainInfo();
      });
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '取消微信授权将无法使用部分功能',
        success: res => {
          if (res.confirm) {
            // wx.setStorageSync("rejectLogin", true);  //用户拒绝登录添加本地缓存状态
            wx.switchTab({
              url: '/pages/index/index'
            })
          }
        }
      })
    }
  },
  //获取首页数据
  getBargainInfo(cb){
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    let data = {
      user_id: app.globalData.userId || wx.getStorageSync('userId'),
      act_id: this.options.act_id
    }
    if (this.options.bar_id) {
      data.bar_id = this.options.bar_id
    }
    wx.request({
      url: app.baseURL + 'Bargain&a=bar_item_detail',
      data: data,
      success: res => {
        if (res.data.status == 0) {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: '活动商品不存在或已结束',
            success: res => {
              if (res.confirm) {
                wx.switchTab({ url: '/pages/index/index' });
              }
            }
          })
        }
        if (res.statusCode == 200) {
          const detail = res.data.item_detail;
          let state;
          // 活动剩余时间倒计时
          const countFun = setInterval(() => {
            detail.sy_time--;  //时间自减
            detail.sy_time < 0 && clearInterval(countFun);  // 时间到了清除定时器
            this.setData({ ['itemInfo.remainingTime']: utils.countDown(detail.sy_time) });
          }, 1000);
          if (this.options.bar_id) {
          // 帮别人砍价，即从别人分享的砍价页面进入
            if (detail.is_help_cut == 1) {
              // 已帮别人砍价
              state = 1;    
            } else if (detail.is_help_cut == 0) {
              // 未帮别人砍价
              state = 2;
            }
          } else {
          // 自己发起，即从商品列表的页面进入
            if (detail.is_bar == 0) {
            // 未帮自己砍价(即自己还未发起砍价活动)
              state = 3;              
            } else if (detail.is_bar == 1) {
            //  已帮自己砍价(无论好友有没有帮自己砍价，第三步只是用来判断是否砍到了最底价)
              if (detail.is_end == 0) {
              // 既未砍到最底价、次数也未用完
                state = 4;
              } else if (detail.is_end == 1) {
              // 已经砍到最底价，或者砍价次数已用完
                state = 5;
              }
            }
          }
          let trendsRatio = ((detail.bar_total_price / (detail.price - detail.act_price)) * 100).toFixed(2);  //进度条比例
          detail.startTime = utils.formatTime(detail.start_time * 1000);  //开始时间
          detail.endTime = utils.formatTime(detail.end_time * 1000);  //结束时间
          WxParse.wxParse('goodsinfo', 'html', detail.intro, this, 0);  //调用wxParse解析html文本

          this.setData({
            itemInfo: detail,
            isStep: state,
            ratio: trendsRatio,
            ['itemInfo.remainingTime']: utils.countDown(detail.sy_time)
          });
          wx.hideLoading();
          typeof cb == "function" && cb();
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    })
  },
  // 显示弹窗
  shareLay: function () {
    this.setData({
      isShareLay: true,
    });
  },
  //关闭弹窗
  cancelShareLay: function () {
    this.setData({
      isShareLay: false,
    });
  },
  //改变轮播图指示点
  changeIndicator: function (e) {
    this.setData({
      isindicator: e.detail.current,
    })
  },

  //立即砍价按钮
  toBargain() {
    wx.showLoading({title: '请稍后...'});
    wx.request({
      url: app.baseURL + 'Bargain&a=self_cut',
      data: {
        user_id: app.globalData.userId,
        act_id: this.options.act_id
      },
      success: res => {
        if (res.statusCode == 200) {
          if (res.data.status == 0) {
            wx.showToast({
              title: res.data.meg,
              icon: 'none',
            })
          }
          if (res.data.status == 3){
            this.setData({
              isLay: true,
              ['itemInfo.bar_id']: res.data.bar_id,
              bargainMoney: res.data.kj_money
            });
            
            wx.hideLoading();
          }
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  //帮砍
  helpBargain() {
    wx.request({
      url: app.baseURL + 'Bargain&a=help_cut',
      data: {
        user_id: app.globalData.userId,
        bar_id: this.options.bar_id
      },
      success: res => {
        if (res.statusCode == 200) {
          if (res.data.status == 6){
            this.setData({
              isLay: true,
              bargainMoney: res.data.kj_money
            });
          } else if (res.data.status == 4 || res.data.status == 5) {
              wx.showModal({
                title: '温馨提示',
                content: '当前商品已经砍价完成，是否重新发起砍价活动？',
                success: (res) => {
                  if (res.confirm) {
                    wx.navigateTo({
                      url: '/pages/bargainDetails/bargainDetails?bar_id=' + this.options.bar_id + '&act_id=' + this.options.act_id,
                    })
                  }
                }
              })
          }else{
            wx.showToast({
              title: res.data.meg,
              icon: 'none'
            });
          }
        }
      },
      fail: function(res) {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    })
  },

  //我也要砍价
  IWantBargain: function () {
    wx.redirectTo({
      url: '/pages/bargainDetails/bargainDetails?act_id=' + this.options.act_id
    })
  },

  //立即购买
  toBuy() {
    const data = this.data.itemInfo;
    wx.navigateTo({
      url: '/pages/placeorder/placeorder?type=3&gui_id=' + data.did + '&item_id=' + data.item_id + '&item_num=' + 1,
    })
  },

  //隐藏砍价成功弹窗遮罩层
  hideLay() {
    this.setData({
      isLay: false
    });
    this.getBargainInfo();
  },

  //隐藏分享弹窗遮罩层
  hideShareLay() {
    this.setData({
      isShareLay: false
    })
  },

  //帮砍用户提示信息
  userInfo() {
    wx.navigateTo({
      url: '/pages/bargainInfo/bargainInfo?bar_id=' + this.data.itemInfo.bar_id
    })
  },

  //海报分享页面
  posterShare() {
    const itemInfo = this.data.itemInfo;
    let info = {
      avatar_url: itemInfo.avatar, // 用户头像
      title: itemInfo.title, // 活动标题
      bar_id: itemInfo.bar_id, // 砍价id
      id: itemInfo.id, // 活动商品id
      // nickname: itemInfo.nickname, // 用户昵称
    }
    wx.navigateTo({
      url: '/pages/posterShare/posterShare?info=' + JSON.stringify(info)
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 刷新数据
    this.data.hasUserInfo?this.getBargainInfo(wx.stopPullDownRefresh()):wx.stopPullDownRefresh();
  },

  // 分享
  // 点击找人帮砍按钮，分享给好友
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
    }
    let data = this.data;
    const imgUrl = 'https://jrtest.0791jr.com/data/attachment/item/' + data.itemInfo.img[0];
    return {
      title: (data.itemInfo.nickname || wx.getStorageSync('userInfo').nickName) + "正在参加" + data.itemInfo.title+"的砍价活动",
      path: '/pages/bargainDetails/bargainDetails?bar_id=' + data.itemInfo.bar_id + '&act_id=' + data.itemInfo.id,
      imageUrl: imgUrl,
      success: res=> {
        // 转发成功
      },
      fail: err => {
        // 转发失败
      },
      complete: res =>{
        this.getBargainInfo();
        this.setData({ isLay: false });
      }
    }
  },
  prevent(){}
})